package net.holmconsulting.database.server.plugin.views;


import java.io.File;
import java.util.ResourceBundle;

import net.holmconsulting.database.server.plugin.Activator;
import net.holmconsulting.database.server.plugin.preferences.PreferenceConstants;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.part.ViewPart;
import org.hsqldb.util.DatabaseManagerSwing;



/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class ServerView extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "net.holmconsulting.database.server.plugin.views.ServerView";
	
	// Start Server Icon
			private static final ImageDescriptor IMG_RUN = ImageDescriptor
					.createFromFile(Activator.class, "/icons/run.gif");

			// Stop Server
			private static final ImageDescriptor IMG_STOP = ImageDescriptor
					.createFromFile(Activator.class, "/icons/stop.gif");

			
			// Logo for View
			private static final ImageDescriptor IMG_LOGO = ImageDescriptor
					.createFromFile(Activator.class, "/icons/databaseServerLogo.png");
			
			private static final ImageDescriptor IMG_CLIENT = ImageDescriptor.createFromFile(Activator.class, "/icons/show_client.gif");
			
			// Locale Specific Resource Bundle
			private static final ResourceBundle BUNDLE = Activator.getResourceBundle();
			
			

	private TableViewer viewer;
	private Action runServer;
	private Action stopServer;
	private Action showClient;
	private Action openPreferences;
	

	/*
	 * The content provider class is responsible for
	 * providing objects to the view. It can wrap
	 * existing objects in adapters or simply return
	 * objects as-is. These objects may be sensitive
	 * to the current input of the view, or ignore
	 * it and always show the same content 
	 * (like Task List, for example).
	 */
	 
	class ViewContentProvider implements IStructuredContentProvider {
		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}
		public void dispose() {
		}
		public Object[] getElements(Object parent) {
			return new String[]{};
		}
	}
	class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object obj, int index) {
			return getText(obj);
		}
		public Image getColumnImage(Object obj, int index) {
			return getImage(obj);
		}
		public Image getImage(Object obj) {
			return PlatformUI.getWorkbench().
					getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
		}
	}
	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public ServerView() {
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		viewer.setInput(getViewSite());

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "net.holmconsulting.database.server.plugin.viewer");
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}


	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				Object obj = ((IStructuredSelection) viewer.getSelection())
						.getFirstElement();
				if (obj != null && obj instanceof File) {
					ServerView.this.fillContextMenu(manager);
				}
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getTable());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(runServer);
		manager.add(stopServer);
		manager.add(new Separator());
		manager.add(showClient);
		manager.add(new Separator());
		manager.add(openPreferences);
	}

	private void fillContextMenu(IMenuManager manager) {
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(runServer);
		manager.add(stopServer);
	}

	public void enableStartServer() {
		if (runServer != null) {
			runServer.setEnabled(true);
		}
	}

	public void disableStartServer() {
		if (runServer != null) {
			runServer.setEnabled(false);
		}
	}

	public void enableStopServer() {
		if (stopServer != null) {
			stopServer.setEnabled(true);
		}
		
		if(showClient != null) {
			showClient.setEnabled(true);
		}
	}

	public void disableStopServer() {
		if (stopServer != null) {
			stopServer.setEnabled(false);
		}
		
		if(showClient != null) {
			showClient.setEnabled(false);
		}
	}
	private void makeActions() {
		openPreferences = new Action() {
			@Override
			public void run() {
				PreferencesUtil
				.createPreferenceDialogOn(
						viewer.getControl().getShell(),
						"net.holmconsulting.database.server.plugin.preferences.PreferencePage",
						new String[] {"net.holmconsulting.database.server.plugin.preferences.PreferencePage" },
						null).open();
			}
		};

		openPreferences.setText(BUNDLE.getString("action.preferences"));
		openPreferences.setToolTipText(BUNDLE
				.getString("action.preferences.tooltip"));

		runServer = new Action() {
			@Override
			public void run() {
				Activator.getDefault().startServer();
			}
		};
		
		showClient = new Action() {
			@Override
			public void run() {
				IPreferenceStore store = Activator.getDefault().getPreferenceStore();
				String username = store.getString(PreferenceConstants.PARAM_USERNAME);
				String password = store.getString(PreferenceConstants.PARAM_PASSWORD);
				
				String databaseName =  store.getString(PreferenceConstants.PARAM_DATABASE_NAME);
				String[] args = new String[] {"--driver","org.hsqldb.jdbcDriver", "--url","jdbc:hsqldb:hsql://localhost/" + databaseName , "--user", username, "--password", password, "-noexit" };
				DatabaseManagerSwing.main(args);
			}
		};
		
		showClient.setText(BUNDLE.getString("action.showclient"));
		showClient.setToolTipText(BUNDLE.getString("action.showclient.tooltip"));
		showClient.setImageDescriptor(IMG_CLIENT);
		showClient.setEnabled(false);

		runServer.setText(BUNDLE.getString("action.start"));
		runServer.setToolTipText(BUNDLE.getString("action.start.tooltip"));
		runServer.setImageDescriptor(IMG_RUN);

		stopServer = new Action() {
			@Override
			public void run() {
				Activator.getDefault().stopServer();
				
			}
		};

		stopServer.setText(BUNDLE.getString("action.stop"));
		stopServer.setToolTipText(BUNDLE.getString("action.stop.tooltip"));
		stopServer.setImageDescriptor(IMG_STOP);
		stopServer.setEnabled(false);
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				// nothing
			}
		});
	}
	
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Server View",
			message);
	}
	
	public TableViewer getViewer() {
		return viewer;
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}